<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class CabinetLiveText extends Model
{
    protected $table = 'xfy_cabinet_live_texts';
    protected $primaryKey = 'id';

    const CONDITION = ['>', '<', '>=', '<=', '='];
    const CONDITION_TEXT = ['>' => '大于', '<' => '小于', '>=' => '大于等于', '<=' => '小于等于', '=' => '等于'];
    const PREFIX = 'LIVETEXT_';


    public static function setTextCache($alias, $data){
        $data['val'] = sprintf("%.3f", $data['val']);
        $one = json_encode($data);
        $key = self::PREFIX.$alias;

        if (Redis::exists($key)) {
            if (!Redis::sismember($key, $one)) {
                Redis::sadd($key, $one);
            }
        } else {
            Redis::sadd($key, $one);
        }
    }

    public static function getTextCache($pointData){
        $res = [];
        foreach ($pointData as $alias => $val) {
            $key = self::PREFIX.$alias;
            if (Redis::exists($key)) {
                $sets = Redis::smembers($key);
                if ($sets) {
                    $name = self::getShowName($sets, $val);
                    if ($name) {
                        $res['live_'.$alias] = $name;
                    }
                }
            }
        }
        return $res;
    }

    public static function getShowName($texts, $val){
        foreach ($texts as $one) {
            $oneText = json_decode($one, true);
            $judgeRes = CabinetAlarmLog::judge($oneText['cond'], $val, $oneText['val']);
            if ($judgeRes) {
                return $oneText['name'];
            }
        }
        return false;
    }

    public static function delTextCache($data){
        $key = self::PREFIX.$data['point_alias'];

        $textData = [
            'name' => $data['name'],
            'cond' => $data['condition'],
            'val' => $data['value'],
        ];
        $one = json_encode($textData);
        Redis::srem($key, $one);
    }
}